<?php
namespace app\controller\productAvatar;

use app\BaseController;
use app\service\productAvatar\ProductAvatar;
use app\service\TopviewApiService;
use think\App;

class Task extends BaseController
{
    // protected $middleware = [AuthMiddleware::class];
    private $marketingVideoService;
    private $apiService;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->marketingVideoService = new ProductAvatar();
        $this->apiService = new TopviewApiService();
    }

    /**
     * 创建营销视频任务（第一阶段：图片替换）
     */
    public function createTask()
    {
        try {
            $params = [
                'taskName' => $this->request->param('taskName', '营销视频任务'),
                'avatarId' => $this->request->param('avatarId'),
                'productImageFileId' => $this->request->param('productImageFileId'),
                'templateImageFileId' => $this->request->param('templateImageFileId'), 
                'userFaceImageFileId' => $this->request->param('userFaceImageFileId'),
                'imageEditPrompt' => $this->request->param('imageEditPrompt')
            ];

            $userId = $this->request->user->uid;
            $result = $this->marketingVideoService->createTask($userId, $params);

            return json([
                'code' => 200,
                'msg' => '任务创建成功',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 开始视频生成（第二阶段：图片转视频）
     */
    public function startVideoGeneration()
    {
        try {
            $taskId = input('taskId/d');
            if (!$taskId) {
                return json(['code' => 400, 'msg' => '任务ID不能为空']);
            }

            $params = [
                'selectedResultKey' => input('selectedResultKey'),
                'mode' => input('mode'),
                'image2videoPrompt' => input('image2videoPrompt'),
                'voiceoverId' => input('voiceoverId'),
                'ttsText' => input('ttsText'),
                'scriptMode' => input('scriptMode'),
                'audioFileId' => input('audioFileId')
            ];

            $userId = $this->request->user->uid;
            $result = $this->marketingVideoService->startVideoGeneration($userId, $taskId, $params);

            return json([
                'code' => 200,
                'msg' => '视频生成任务提交成功',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取任务列表
     */
    public function getTaskList()
    {
        try {
            $page = input('page/d', 1);
            $pageSize = input('pageSize/d', 10);
            $userId = $this->request->user->uid;

            $result = $this->marketingVideoService->getTaskList($userId, $page, $pageSize);

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取任务详情
     */
    public function getTaskDetail()
    {
        try {
            $taskId = input('taskId/d');
            if (!$taskId) {
                return json(['code' => 400, 'msg' => '任务ID不能为空']);
            }

            $userId = $this->request->user->uid;
            $result = $this->marketingVideoService->getTaskDetail($userId, $taskId);

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 手动检查图片替换任务状态（开发测试用）
     */
    public function checkReplaceTaskStatus()
    {
        try {
            $taskId = input('taskId/d');
            if (!$taskId) {
                return json(['code' => 400, 'msg' => '任务ID不能为空']);
            }

            $userId = $this->request->user->uid;
            $task = $this->marketingVideoService->getTaskDetail($userId, $taskId);

            if (!$task['replace_task_id']) {
                return json(['code' => 400, 'msg' => '替换任务ID不存在']);
            }

            // 调用API查询替换任务状态
            $result = $this->apiService->queryImageReplaceTask($task['replace_task_id']);
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 手动检查视频生成任务状态（开发测试用）
     */
    public function checkVideoTaskStatus()
    {
        try {
            $taskId = input('taskId/d');
            if (!$taskId) {
                return json(['code' => 400, 'msg' => '任务ID不能为空']);
            }

            $userId = $this->request->user->uid;
            $task = $this->marketingVideoService->getTaskDetail($userId, $taskId);

            if (!$task['video_task_id']) {
                return json(['code' => 400, 'msg' => '视频任务ID不存在']);
            }

            // 调用API查询视频任务状态
            $result = $this->apiService->queryImage2VideoTask($task['video_task_id']);
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取图片替换状态
     * @param int $taskId 任务ID
     * @return array [
     *     'status' => 'processing|completed|failed',  // 状态：处理中|已完成|失败
     *     'message' => string,  // 状态说明
     *     'error_msg' => string|null  // 如果失败，错误信息
     * ]
     */
    public function getReplaceStatus($taskId)
    {
        try {
            $userId = $this->request->user->uid;
            $task = $this->marketingVideoService->getTaskDetail($userId, $taskId);
            
            if (!$task) {
                return [
                    'status' => 'failed',
                    'message' => '任务不存在',
                    'error_msg' => '任务不存在'
                ];
            }

            // 根据replace_status判断状态
            switch ($task['replace_status']) {
                case 0: // 待处理
                case 1: // 处理中
                    return [
                        'status' => 'processing',
                        'message' => '图片替换处理中',
                        'error_msg' => null
                    ];
                case 2: // 已完成
                    return [
                        'status' => 'completed',
                        'message' => '图片替换已完成',
                        'error_msg' => null
                    ];
                case 3: // 失败
                    return [
                        'status' => 'failed',
                        'message' => '图片替换失败',
                        'error_msg' => $task['replace_error_msg'] ?? '未知错误'
                    ];
                default:
                    return [
                        'status' => 'failed',
                        'message' => '未知状态',
                        'error_msg' => '任务状态异常'
                    ];
            }
        } catch (\Exception $e) {
            return [
                'status' => 'failed',
                'message' => '获取状态失败',
                'error_msg' => $e->getMessage()
            ];
        }
    }
} 